/*
 * BookJFrame.java
 *
 * Created on 8.5.2011, 20:09:12
 */

package cz.muni.fi.pv168.confusinglibrary.app.gui;

import cz.muni.fi.pv168.confusinglibrary.libs.Author;
import cz.muni.fi.pv168.confusinglibrary.libs.AuthorManager;
import cz.muni.fi.pv168.confusinglibrary.libs.Book;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;

/**
 *
 * @author GNeps
 */
public class BookFormJFrame extends javax.swing.JFrame {

    private MainJFrame main;
    private ResourceBundle bundle = java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/confusinglibrary/app/language/language");
    private AuthorManager authorManager;
    private Book book;
    private Integer row;

    /** Creates new form BookJFrame */
    public BookFormJFrame(MainJFrame main, AuthorManager authorManager, Book book, int row) {
        this.main = main;
        this.authorManager = authorManager;
        this.book = book;
        this.row = row;
        initComponents();
        this.setTitle(bundle.getString("title_update_book"));
        setUpInformation(book);
    }

    /** Creates new form BookJFrame */
    public BookFormJFrame(MainJFrame main, AuthorManager authorManager) {
        this.main = main;
        this.authorManager = authorManager;
        initComponents();
        this.setTitle(bundle.getString("title_add_book"));
    }

    private void setUpInformation(Book book) {
        jTextFieldName.setText(book.getName());
        jTextFieldAuthor.setText(book.getAuthor().getSurname());
        jCheckBoxFiction.setSelected(book.isFiction());

        SimpleDateFormat sdf = new SimpleDateFormat(bundle.getString("date_format"));
        Date date = book.getPublished();
        if (date != null) {
            jTextFieldPublished.setText(sdf.format(date));
        } else {
            jTextFieldPublished.setText("");
        }

        jTextAreaDescription.setText(book.getDescription() != null ? book.getDescription() : "");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextAreaDescription = new javax.swing.JTextArea();
        jTextFieldName = new javax.swing.JTextField();
        jTextFieldAuthor = new javax.swing.JTextField();
        jTextFieldPublished = new javax.swing.JTextField();
        jButtonOK = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();
        jCheckBoxFiction = new javax.swing.JCheckBox();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jScrollPane2.setViewportView(jTextArea2);

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("cz/muni/fi/pv168/confusinglibrary/app/language/language"); // NOI18N
        jTextField1.setText(bundle.getString("BookFormJFrame.jTextField1.text")); // NOI18N

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel1.setText(bundle.getString("book_name")); // NOI18N

        jLabel2.setText(bundle.getString("book_author")); // NOI18N

        jLabel3.setText(bundle.getString("book_fiction")); // NOI18N

        jLabel4.setText(bundle.getString("book_published")); // NOI18N

        jLabel5.setText(bundle.getString("book_description")); // NOI18N

        jTextAreaDescription.setColumns(20);
        jTextAreaDescription.setRows(5);
        jScrollPane3.setViewportView(jTextAreaDescription);

        jTextFieldName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldNameActionPerformed(evt);
            }
        });

        jTextFieldPublished.setToolTipText(bundle.getString("tool_tip_date")); // NOI18N

        jButtonOK.setText(bundle.getString("ok")); // NOI18N
        jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOKActionPerformed(evt);
            }
        });

        jButtonCancel.setText(bundle.getString("cancel")); // NOI18N
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jCheckBoxFiction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBoxFictionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jLabel5)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jCheckBoxFiction)
                            .addComponent(jTextFieldName, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                            .addComponent(jTextFieldAuthor, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
                            .addComponent(jTextFieldPublished, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButtonOK)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldAuthor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jCheckBoxFiction))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldPublished, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonCancel)
                    .addComponent(jButtonOK))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        main.setBookButtons(true);
    }//GEN-LAST:event_formWindowClosed

    private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
        if (book == null) {
            book = new Book();
        }
        String error = "";

        if (jTextFieldName.getText().trim().length() > 100) {
            error += bundle.getString("error_name_length") + "\n";
        } else if (jTextFieldName.getText().trim().length() == 0) {
            error += bundle.getString("error_empty_name") + "\n";
        } else {
            book.setName(jTextFieldName.getText().trim());
        }

        try {
            List<Author> authors = authorManager.findAuthorsByName(jTextFieldAuthor.getText().trim());
            if (authors.size() > 0) {
                book.setAuthor(authors.get(0));
            } else {
                error += bundle.getString("error_author_not_found") + "\n";
            }
        } catch (IllegalArgumentException ex) {
            error += bundle.getString("error_author_not_found") + "\n";
        }

        try {
            book.setPublished(createDate(jTextFieldPublished.getText().trim()));
        } catch (ParseException ex) {
            error += bundle.getString("error_published_format") + "\n";
        } catch (IllegalArgumentException ex) {
            error += bundle.getString("error_published") + "\n";
        }

        book.setFiction(jCheckBoxFiction.isSelected());

        if (!jTextAreaDescription.getText().trim().equals("")) {
            book.setDescription(jTextAreaDescription.getText().trim());
        }
        
        if (!error.equals("")) {
            JOptionPane.showMessageDialog(this, error, bundle.getString("title_error"), JOptionPane.ERROR_MESSAGE);
        } else {
            if (row != null) {
                main.updateBook(book, row);
            } else {
                main.addBook(book);
            }
            this.dispose();
        }
    }//GEN-LAST:event_jButtonOKActionPerformed

    private void jTextFieldNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldNameActionPerformed

    private void jCheckBoxFictionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxFictionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBoxFictionActionPerformed

    private Date createDate(String stringDate) throws ParseException {
        if (stringDate.equals("")) {
            return null;
        }
        SimpleDateFormat fmt = new SimpleDateFormat(bundle.getString("date_format"));
        return fmt.parse(stringDate);
    }

    public static void startWindow(final MainJFrame main, final AuthorManager authorManager,
                                   final Book book, final int row) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BookFormJFrame(main, authorManager, book, row).setVisible(true);
            }
        });
    }

    public static void startWindow(final MainJFrame main, final AuthorManager authorManager) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BookFormJFrame(main, authorManager).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonOK;
    private javax.swing.JCheckBox jCheckBoxFiction;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextArea jTextAreaDescription;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextFieldAuthor;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldPublished;
    // End of variables declaration//GEN-END:variables

}
